package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.mapper.*;
import com.woniu.pojo.Book;
import com.woniu.pojo.Card;
import com.woniu.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.BookQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dong
 * @since 2022-10-13
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {

    @Autowired(required = false)
    private BookMapper bookMapper;
    @Autowired(required = false)
    private CardMapper cardMapper;
    @Autowired(required = false)
    private MemberCardMapper memberCardMapper;
    @Autowired(required = false)
    private TimetableMapper timetableMapper;

    /**
     * 预约列表模糊分页查询
     * @param currentPage
     * @param pageSize
     * @param bookQueryVo
     * @return
     */
    public PageResult search(Integer currentPage, Integer pageSize, BookQueryVo bookQueryVo) {
        // 创建分页对象
        IPage<Book> iPage = new Page<>(currentPage, pageSize);
        IPage<Map<String, Object>> bookIPage = bookMapper.selectByVoPage(iPage, bookQueryVo);
        return new PageResult(bookIPage.getTotal(), bookIPage.getRecords());
    }

    /**
     * 根据ID修改状态
     * @param bookId
     * @param status
     * @return
     */
    public boolean updateByStatus(String bookId, String status) {
        return bookMapper.modifyById(bookId,status);
    }

    /**
     * 预约课程
     * @param memberId
     * @param cardId
     * @param timetableId
     * @param discount
     */
    public void book(String memberId, String cardId, String timetableId, BigDecimal discount) {
        Book book = new Book();
        book.setTimetableId(timetableId);
        book.setMemberId(memberId);
        bookMapper.insert(book);
        Card card = cardMapper.selectById(cardId);
        Integer type = card.getType();
        if(type == 0){
            memberCardMapper.updateOne(memberId, cardId);
        }else{
            BigDecimal cost = timetableMapper.selectCost(timetableId);
            cost = cost.multiply(discount);
            memberCardMapper.updateTwo(cost, memberId, cardId);
        }
    }
}
